package msgtransfer

import (
	"context"
	"encoding/json"

	"gitee.com/gao-deguang/easy-chat/apps/im/models"
	"gitee.com/gao-deguang/easy-chat/apps/im/ws/ws"
	"gitee.com/gao-deguang/easy-chat/apps/task/mq/internal/svc"
	"gitee.com/gao-deguang/easy-chat/apps/task/mq/mq"
	"gitee.com/gao-deguang/easy-chat/pkg/bitmap"
	"github.com/zeromicro/go-zero/core/logx"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type MsgChatTransfer struct {
	*baseMsgTransfer
}

func NewMsgChatTransfer(svc *svc.ServiceContext) *MsgChatTransfer {
	return &MsgChatTransfer{
		baseMsgTransfer: NewbaseMsgTransfer(svc),
	}
}

func (m *MsgChatTransfer) Consume(ctx context.Context, key, value string) error {
	//fmt.Println("key:", key, "value:", value)

	var (
		data  mq.MsgChatTransfer
		msgId = primitive.NewObjectID()
	)

	if err := json.Unmarshal([]byte(value), &data); err != nil {
		return err
	}
	//记录到数据库中
	if err := m.addChatlogToMongodb(ctx, msgId, data); err != nil {
		return err
	}

	logx.Info("msgChatTransfer的转发地址RecvServerAddr: ", data.SendServerAddr)
	return m.Transfer(ctx, &ws.Push{
		MsgId:          msgId.Hex(),
		ConversationId: data.ConversationId,
		ChatType:       data.ChatType,
		SendId:         data.SendId,
		RecvServerAddr: data.SendServerAddr,
		RecvId:         data.RecvId,
		RecvIds:        data.RecvIds,
		SendTime:       data.SendTime,
		Mtype:          data.Mtype,
		Content:        data.Content,
	})
}

// func (m *MsgChatTransfer) single(ctx context.Context, data *mq.MsgChatTransfer) error {
// 	logx.Info("推送消息给wsClient推送消息给wsClient推送消息给wsClient推送消息给wsClient推送消息给wsClient")
// 	err := m.svcCtx.WsClients[].Send(websocket.Message{
// 		FrameType: websocket.FrameData,
// 		Method:    "push",
// 		FromId:    constant.SYSTEM_ROOT,
// 		Data:      data,
// 	})
// 	if err != nil {
// 		return err
// 	}
// 	return nil
// }

// func (m *MsgChatTransfer) group(ctx context.Context, data *mq.MsgChatTransfer) error {
// 	users, err := m.svcCtx.Social.GroupUsers(ctx, &social.GroupUserReq{
// 		GroupId: data.RecvId,
// 	})
// 	if err != nil {
// 		return nil
// 	}

// 	data.RecvIds = make([]string, 0, len(users.List))

// 	for _, member := range users.List {
// 		if member.UserId == data.SendId {
// 			continue
// 		}

// 		data.RecvIds = append(data.RecvIds, member.UserId)
// 	}

// 	err = m.svcCtx.WsClient.Send(websocket.Message{
// 		FrameType: websocket.FrameData,
// 		Method:    "push",
// 		FromId:    constant.SYSTEM_ROOT,
// 		Data:      data,
// 	})
// 	if err != nil {
// 		return err
// 	}
// 	return nil
// }

func (l *MsgChatTransfer) addChatlogToMongodb(ctx context.Context, msgId primitive.ObjectID, data mq.MsgChatTransfer) error {
	chatLog := models.ChatLog{
		ID:             msgId,
		ConversationId: data.ConversationId,
		ChatType:       data.ChatType,
		SendId:         data.SendId,
		RecvId:         data.RecvId,
		MsgType:        data.Mtype,
		MsgContent:     data.Content,
		SendTime:       data.SendTime,
	}

	readRecords := bitmap.NewBitmap(250)
	readRecords.Set(chatLog.SendId)
	chatLog.ReadRecords, _ = readRecords.Export()

	//将消息插入数据库
	err := l.svcCtx.ChatLogModel.Insert(ctx, &chatLog)
	if err != nil {
		return err
	}

	//完成对会话的更新
	err = l.svcCtx.ConversationModel.UpdateMsg(ctx, &chatLog)
	if err != nil {
		return err
	}
	return nil
}
